package com.jch.ft.server;

import com.alibaba.fastjson.JSON;
import com.jch.ft.domain.*;
import com.jch.ft.util.CacheUtil;
import com.jch.ft.util.FileUtil;
import com.jch.ft.util.MsgUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.text.SimpleDateFormat;
import java.util.Date;

// 处理文件上传|分片传输、断点传输
public class ServerFileTransferHandler extends ChannelInboundHandlerAdapter {

    private final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (!(msg instanceof FileTransferProtocol)) return;
        FileTransferProtocol fileTransferProtocol = (FileTransferProtocol) msg;
        switch(fileTransferProtocol.getTransferType()){
            case 0:
                FileDescInfo fileDescInfo = (FileDescInfo) fileTransferProtocol.getTransferObject();
                // 断点续传信息，实际应用中需要将断点续传信息保存到数据库中
                FileBurstInstruct fileBurstInstructOld = CacheUtil.burstDataMap.get(fileDescInfo.getFileName());
                if (null != fileBurstInstructOld) {
                    if (fileBurstInstructOld.getStatus() == Constants.FileStatus.COMPLETE){
                        CacheUtil.burstDataMap.remove(fileDescInfo.getFileName());
                    }
                    System.out.println(format.format(new Date()) +" 断点续传: " + JSON.toJSONString(fileBurstInstructOld));
                    ctx.writeAndFlush(MsgUtil.buildTransferInstruct(fileBurstInstructOld));
                    return;
                }
                // 发送传输指令
                FileTransferProtocol send = MsgUtil.buildTransferInstruct(Constants.FileStatus.BEGIN,fileDescInfo.getFileUrl(),0);
                ctx.writeAndFlush(send);
                System.out.println(format.format(new Date()) + " 客户端发出文件传输请求：" + JSON.toJSONString(fileDescInfo));
                break;
            case 2:
                FileBurstData fileBurstData = (FileBurstData) fileTransferProtocol.getTransferObject();
                FileBurstInstruct fileBurstInstruct = FileUtil.writeFile("E:/open-sourcing/learn-netty/netty-expand/file-transfer/",fileBurstData);

                CacheUtil.burstDataMap.put(fileBurstData.getFileName(),fileBurstInstruct);

                ctx.writeAndFlush(MsgUtil.buildTransferInstruct(fileBurstInstruct));
                System.out.println(format.format(new Date()) + " 接收客户端传输文件数据: " + JSON.toJSONString(fileBurstData));

                if (fileBurstInstruct.getStatus() == Constants.FileStatus.COMPLETE){
                    CacheUtil.burstDataMap.remove(fileBurstData.getFileName());
                }
                break;
            default:
                break;
        }
    }
}
